<!-- 添加建筑群/园区 -->
<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" :before-close="handleCloseBindWarnStandard" :close-on-click-modal="false" :title="title" width="940px" height="300px">
      <el-form v-loading="formLoading" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="120px" class="twoColumn">
        <el-form-item label="所属单位" prop="corp_id">
          <el-input v-if="dialogType === '修改'" v-model="dialogForm.corp_name" placeholder="" class="el-disabled" readonly="readonly" autocomplete="off"/>
          <el-select v-else v-model="dialogForm.corp_id" clearable filterable allow-create default-first-option autocomplete="off" placeholder="请输入单位名称">
            <el-option v-for="item in companyList" :key="item.corp_id" :label="item.name" :value="item.corp_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑群名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入建筑群名称" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="园区平面图" prop="plan" class="img-form-item">
          <img v-if="!uploadSuccess&&dialogForm.plan.length" :src="dialogForm.plan" @click="uploadBtn" >
          <img v-if="uploadSuccess&&!dialogForm.plan.length" :src="plan" @click="uploadBtn">
          <i v-if="!uploadSuccess&&dialogForm.plan.length === 0" :class="uploadClass" @click="uploadBtn" />
          <input id="upload" name="plan" type="file" accept="image/*" @change="upload">
        </el-form-item>
        <div class="img-column">
          <el-form-item label="地区/详细地址" prop="address" class="regionAddCombination">
            <el-cascader
              :options="options"
              v-model="selectedOptions"
              :props="optionProps"
              size="large"
              filterable
              clearable
              @change="handleChange" />
            <i>-</i>
            <el-input v-model="dialogForm.address" placeholder="请输入详细地址" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="所在经纬度" prop="longitude" class="mapInfo">
            <el-input v-model="dialogForm.longitude" placeholder="请输入经度" autocomplete="off"/>
            <el-input v-model="dialogForm.latitude" placeholder="请输入纬度" autocomplete="off"/>
            <i class="el-icon-location-outline" @click="manualPickup"/>
          </el-form-item>
        </div>
        <el-form-item label="联系人" prop="link_user">
          <el-input v-model="dialogForm.link_user" placeholder="请输入联系人" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="联系人手机号" prop="link_user_mobile">
          <el-input v-model="dialogForm.link_user_mobile" placeholder="请输入联系人手机号" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="建筑总数" prop="total_building">
          <el-input-number v-model="dialogForm.total_building" :min="1" label="请输入建筑总数"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleMap" title="手动拾取" width="600px" height="400px">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px">
        <el-form-item label="所在经纬度" class="mapInfo-map">
          <el-input v-model="dialogForm.longitude" readonly="readonly" autocomplete="off"/>
          <el-input v-model="dialogForm.latitude" readonly="readonly" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="地区/详细地址">
          <el-input v-model="address" readonly="readonly" autocomplete="off"/>
        </el-form-item>
        <div id="container" style="width:560px;height:300px;"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisibleMap = false">确 定</el-button>
        <el-button @click="dialogVisibleMap = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import $ from 'jquery'
import { parksAdd, parksUpdate } from '@/api/park'
import { getRegion } from '@/api/common'
import AMap from 'AMap'
import { getSocialUnit } from '@/api/company'
// import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { validateMobile } from '@/utils/validate'
const isMobile = (rule, value, callback) => {
  if (!validateMobile(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    dialogForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogType: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      uploadSuccess: false,
      uploadClass: 'el-icon-plus avatar-uploader-icon', // el-icon-check
      title: '',
      options: [],
      optionProps: {
        value: 'area_id',
        label: 'area_name',
        children: 'list'
      },
      address: '',
      plan: '',
      selectedOptions: [],
      requestFn: {},
      companyList: [],
      // 添加form验证
      rules: {
        corp_id: [{
          required: true,
          message: '请选择单位',
          trigger: 'change'
        }],
        name: [{
          required: true,
          message: '请输入建筑群名称',
          trigger: 'blur'
        }],
        plan: [{
          required: true,
          message: '请上传平面图',
          trigger: 'blur'
        }],
        province: [{
          required: true,
          message: '请选择地区',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请输入详细地址',
          trigger: 'blur'
        }],
        longitude: [{
          required: true,
          message: '请输入所在经纬度',
          trigger: 'blur'
        }],
        link_user: [{
          required: true,
          message: '请输入联系人',
          trigger: 'blur'
        }],
        total_building: [{
          required: true,
          message: '请输入建筑总数',
          trigger: 'blur'
        }],
        link_user_mobile: [{
          validator: isMobile,
          trigger: 'blur'
        }]
      },
      companyType: this.GLOBAL.companyType,
      formLoading: false,
      // 地图
      dialogVisibleMap: false,
      showTopMenu: false
    }
  },
  watch: {
    dialogType(val) {
      this.init(val)
    },
    dialogForm(val) {
      this.dialogForm = val
      this.selectedOptions = []
      this.selectedOptions.push(this.dialogForm.province + '')
      this.selectedOptions.push(this.dialogForm.city + '')
      this.selectedOptions.push(this.dialogForm.district + '')
    },
    dialogVisible(val) {
      if (val) {
        this.uploadSuccess = false
        this.uploadClass = 'el-icon-plus avatar-uploader-icon'
        $('#upload').val('')
      }
    }
  },
  mounted() {
    this.init(this.dialogType)
  },
  created() {
    if (sessionStorage.getItem('corpType') && sessionStorage.getItem('corpType') === '2') {
      this.showTopMenu = false
    } else {
      this.showTopMenu = true
      this.getCompanyList()
    }
    this.getRegion()
  },
  methods: {
    init(val) {
      if (val === '添加') {
        this.title = '添加建筑群'
        this.requestFn = parksAdd
        this.selectedOptions = []
      } else if (val === '修改') {
        this.title = '修改建筑群'
        this.requestFn = parksUpdate
        this.selectedOptions = []
        this.selectedOptions.push(this.dialogForm.province + '')
        this.selectedOptions.push(this.dialogForm.city + '')
        this.selectedOptions.push(this.dialogForm.district + '')
      }
    },
    initMap() {
      var that = this
      const map = new AMap.Map('container', {
        center: [116.397428, 39.90923],
        resizeEnable: true,
        zoom: 10
      })
      var geocoder = new AMap.Geocoder()
      var address = ''
      var cityList = []
      var districtList = []
      that.options.forEach(function(value, index, array) {
        if (array[index].area_id === that.dialogForm.province) {
          address += array[index].area_name
          cityList = array[index].list
        }
      })
      cityList.forEach(function(value, index, array) {
        if (array[index].area_id === that.dialogForm.city) {
          address += array[index].area_name
          districtList = array[index].list
        }
      })
      districtList.forEach(function(value, index, array) {
        if (array[index].area_id === that.dialogForm.district) {
          address += array[index].area_name
        }
      })
      address += that.dialogForm.address
      this.address = address
      geocoder.getLocation(address, function(status, result) {
        if (status === 'complete' && result.geocodes.length) {
          map.clearMap()
          var marker = new AMap.Marker()
          var lnglat = result.geocodes[0].location
          that.dialogForm.longitude = lnglat.lng
          that.dialogForm.latitude = lnglat.lat
          marker.setPosition(lnglat)
          marker = new AMap.Marker({
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            position: lnglat
          })
          map.add(marker)
          map.setFitView(marker)
        } else {
          that.$message({
            message: '根据地址查询位置失败',
            type: 'warning'
          })
        }
      })
      AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function() {
        map.addControl(new AMap.ToolBar())
        map.addControl(new AMap.Scale())
      })
      var oldLng = that.dialogForm.longitude
      var oldLat = that.dialogForm.latitude
      var marker
      if (oldLng !== '' && oldLat !== '') {
        marker = new AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: [oldLng, oldLat]
        })
        map.add([marker])
        map.setFitView()
      }
      map.on('click', function(e) {
        const { lng, lat } = e.lnglat
        // 先删除上个标注
        var oldLng = that.dialogForm.longitude
        var oldLat = that.dialogForm.latitude
        var marker
        if (oldLng !== '' && oldLat !== '') {
          map.clearMap()
        }
        var address
        that.dialogForm.longitude = lng
        that.dialogForm.latitude = lat
        marker = new AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: [that.dialogForm.longitude, that.dialogForm.latitude]
        })
        map.add([marker])
        map.setFitView()
        // 这里通过高德 SDK 完成。
        var geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: 'base'
        })
        // 设置label标签
        geocoder.getAddress([that.dialogForm.longitude, that.dialogForm.latitude], function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              var addr = result.regeocode.addressComponent
              // 具体地址
              that.dialogForm.address = addr.township + addr.street + addr.streetNumber
              // 省
              that.dialogForm.province = result.regeocode.addressComponent.province
              // 市
              that.dialogForm.city = result.regeocode.addressComponent.city === '' ? that.dialogForm.province : result.regeocode.addressComponent.city
              // 区
              that.dialogForm.district = result.regeocode.addressComponent.district
              // 回填下拉框
              address = that.dialogForm.province + that.dialogForm.city + that.dialogForm.district + that.dialogForm.address
              that.address = address
              that.selectedOptions = []
              var cityList = []
              var districtList = []
              if (that.dialogForm.province !== '') {
                that.options.forEach(function(value, index, array) {
                  if (array[index].area_name === that.dialogForm.province) {
                    that.selectedOptions.push(array[index].area_id)
                    cityList = array[index].list
                  }
                })
                cityList.forEach(function(value, index, array) {
                  if (array[index].area_name === that.dialogForm.city) {
                    that.selectedOptions.push(array[index].area_id)
                    districtList = array[index].list
                  }
                })
                districtList.forEach(function(value, index, array) {
                  if (array[index].area_name === that.dialogForm.district) {
                    that.selectedOptions.push(array[index].area_id)
                  }
                })
              }
              if (that.selectedOptions.length !== 3) {
                that.$message({
                  message: '地址匹配失败，请手动选择省市区',
                  type: 'warning'
                })
              }
              that.$nextTick()
            }
          } else {
            that.$message({
              message: '地址获取失败',
              type: 'warning'
            })
          }
        })
      })
    },
    handleChange(val) {
      if (val.length > 0) {
        this.dialogForm.province = val[0]
        this.dialogForm.city = val[1]
        this.dialogForm.district = val[2]
      } else {
        this.selectedOptions = []
        this.dialogForm.province = ''
        this.dialogForm.city = ''
        this.dialogForm.district = ''
      }
    },
    submitForm(val) {
      if (this.dialogForm.plan === '') {
        this.$message({
          message: '请上传平面图',
          type: 'warning'
        })
        return false
      }
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const that = this
          const image = new FormData()
          var params = {
            ...that.dialogForm
          }
          if (params.plan.length) {
            params.plan = ''
          }
          if (that.selectedOptions) {
            params.province = that.selectedOptions[0]
            params.city = that.selectedOptions[1]
            params.district = that.selectedOptions[2]
          }
          for (const item in params) {
            image.append(item, params[item])
          }
          const obj = {
            fileType: 'file',
            data: image,
            park_id: that.dialogForm.park_id
          }
          that.requestFn(obj)
            .then((res) => {
              that.formLoading = false
              const data = res.data
              if (data.code === 40000) {
                that.$message.success(data.message)
                that.$emit('submitForm', this.dialogForm)
              } else {
                that.$message.warning(data.message)
              }
            })
            .catch((err) => {
              console.log(err)
              that.formLoading = false
            })
        }
      })
    },
    // 点击上传按钮
    uploadBtn(index) {
      $('#upload').click()
    },
    // 上传成功
    upload(e) {
      const isImage = e.target.files[0].type.substr(0, 5) === 'image'
      if (isImage) {
        this.uploadSuccess = true
        this.uploadClass = 'el-icon-check avatar-uploader-icon'
        this.dialogForm.plan = e.target.files[0]
        this.plan = URL.createObjectURL(this.dialogForm.plan)
      } else {
        this.$message.error('请上传图片格式!')
      }
    },
    // 关闭弹窗
    handleCancel() {
      this.$emit('getCancel')
    },
    // 关闭弹窗，不可以删这个方法。不用这个方法点击遮罩层关闭会报错
    handleCloseBindWarnStandard() {
      this.$emit('closeBindWarnStandard')
    },
    handleAvatarSuccess(res, file) {
      this.dialogForm.plan = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
    manualPickup() {
      this.dialogVisibleMap = true
      this.$nextTick(function() {
        this.initMap()
      })
    },
    getCompanyList() {
      const that = this
      getSocialUnit()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            that.companyList = []
            if (that.companyList && response.data.data.length > 0) {
              that.companyList = response.data.data
            }
          }
        })
        .catch(() => {
          this.companyList = []
        })
    },
    // 获取省市区
    getRegion() {
      const that = this
      getRegion()
        .then((res) => {
          const data = res.data
          if (data.code === 40000) {
            that.options = data.data
          } else {
            that.$message.warning(data.message)
          }
        })
        .catch((err) => {
          console.log(err)
          that.formLoading = false
        })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.img-column{
  width: 50%;
  height: 118px;
  float: left;
  .el-form-item{
    width: 100%;
    float: left;
  }
}
.img-tips{
	font-size: 13px;
	font-weight: 900;
	color: #D13E3E;
}
.img-form-item{
  margin-bottom: 0px;
  position: relative;
  span{
    position: absolute;
    display: block;
    width: 104px;
    text-align: center;
    left: 0;
    top: 65px;
  }
  img{
    max-width: 100%;
    height: 104px;
    display: block;
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 104px;
  height: 104px;
  line-height: 104px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon:hover{
  border-color: #409EFF;
}
.avatar {
  width: 104px;
  height: 104px;
  display: block;
}
// 地区、地址
.regionAddCombination{
  .el-cascader{
    width: 160px;
  }
  .el-input{
    width: 136px;
  }
}
// 经纬度
.mapInfo{
  position:relative;
  .el-input{
    width: 136px;
  }
  i{
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    width: 30px;
    height: 36px;
    line-height: 36px;
    text-align: center;
    font-size: 20px;
    cursor: pointer;
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  }
  i:hover{
    border-color: #C0C4CC;
  }
}
#upload {
  display: none;
}
.mapInfo-map{
  .el-input{
    width: 49.5%;
  }
}
#map{
  width:100%;
  height: 300px;
}
.amap-demo{
  height: 300px;
}
</style>
